﻿using FarmSmartSleep.Common.Domain;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace FarmSmartSleep.Organ.API.Application.Commands.DepartmentCommands
{
    public class DepartTreeSearchHandler : IRequestHandler<DepartTreeSearchCommand, Result>
    {
        private readonly IBaseRepository<DepartTree> treebaseRepository;

        public DepartTreeSearchHandler(IBaseRepository<DepartTree> treebaseRepository)
        {
            this.treebaseRepository = treebaseRepository;
        }
        /// <summary>
        /// 部门级联的显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(DepartTreeSearchCommand request, CancellationToken cancellationToken)
        {
            var result=new Result() { Code=(int)CodeEnum.search};
            var list=treebaseRepository.GetAll().Where(x=>x.Pid==0).ToList();
            List<Cascard> cascards = new List<Cascard>();
            foreach (var item in list)
            {
                Cascard cascard = new Cascard();
                cascard.value=item.DepartTreeId;
                cascard.label = item.DepartTreeName;
                cascard.children=GetCascards(item.DepartTreeId);
                cascards.Add(cascard);
            }
            result.Data= cascards;
            return result;
        }
        /// <summary>
        /// 级联
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public List<Cascard> GetCascards(int pid=0)
        {
            var list=treebaseRepository.GetAll().Where(x=>x.Pid == pid).ToList();
            List<Cascard> cascards = new List<Cascard>(); 
            foreach(var item in list)
            {
                Cascard cascard = new Cascard();
                cascard.value=item.DepartTreeId;
                cascard.label=item.DepartTreeName;
                cascard.children=GetCascards(item.DepartTreeId);
                cascards.Add(cascard);
            }
            return cascards;
        }
        
    }
}
